package com.jielihaofeng.nettyadvance.stickyandhalfbag;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

/**
 * @author Johnnie Wind
 * @description 预设长度解码测试
 * @date 2021/11/15 15:40
 */
public class TestLengthFieldDecode {
    public static void main(String[] args) {
            EmbeddedChannel channel = new EmbeddedChannel(
                new LengthFieldBasedFrameDecoder(1024, 0, 4, 1, 4),
                new LoggingHandler(LogLevel.DEBUG)
        );

        // 4个字节长度，实际内容
        ByteBuf buffer = ByteBufAllocator.DEFAULT.buffer();
        send(buffer, "hello world");
        send(buffer, "jielihaofeng");
        channel.writeInbound(buffer);
    }

    public static void send(ByteBuf buffer, String content) {
        byte[] bytes = content.getBytes();
        int length = bytes.length;
        // 长度字节，对应lengthFieldLength参数
        buffer.writeInt(length);
        // 长度之后的额外字节，对应lengthAdjustment参数
        buffer.writeByte(1);
        buffer.writeBytes(bytes);
    }
}
